<?php

namespace App\Api;

use PhalApi\Api;
use PhalApi\Exception\BadRequestException;
use PhpOffice\PhpWord\TemplateProcessor;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
// 引入七牛云存储类
use Qiniu\Storage\BucketManager;

/**
 * 保存签名
 *   @desc 保存签名
 */
class HongKongImg extends Api
{

    public function getRules()
    {
        return array(
            'SaveImg' => array(
                'base64'  => array('name' => 'base64', 'require' => true, 'desc' => 'base64'),
                // 'idcard'  => array('name' => 'idcard', 'require' => true, 'min'=>5,  'desc' => 'idcard'),
            ),
            'SaveInfo' => array(),
            'qiNiuToken' => array(),
            'ZhjlqiNiuToken' => array(),
            'getCourse' => array(),
            'getQiniuUploadToken' => array(
                'keys' => array('name' => 'keys', 'require' => true, 'desc' => 'keys'),
            ),
        );
    }

    /**
     * 香港课程价格
     * @desc getCourse
     * @return array data 签名url
     * @exception 400 非法请求，参数传递错误
     */
    public function getCourse()
    {
        // 最简单的处理方式
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: *');

        $safety = 210;
        $Revalidation = 170;

        return array(
            'safety' => $safety,
            'Revalidation' => $Revalidation,
        );
    }


    /**
     * 七牛token
     * @desc 七牛token
     * @return array data 签名url
     * @exception 400 非法请求，参数传递错误
     */
    public function ZhjlqiNiuToken()
    {
        // 最简单的处理方式
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: *');

        $accessKey = '-a9BiSqOW1dT8vk2Clgy70WnQtQ1z3UHukk7AFB-';
        $secretKey = 'KikooIMw2B2nlpZw_ihn_3MQ226AlGuzYha8OL9R';
        // 初始化签权对象
        $auth = new Auth($accessKey, $secretKey);

        $bucket = 'sbzs';

        // 生成上传Token
        $token = $auth->uploadToken($bucket);
        return array(
            'token' => $token,
            'key' => $secretKey
        );

    }
    

    /**
     * 七牛token
     * @desc 七牛token
     * @return array data 签名url
     * @exception 400 非法请求，参数传递错误
     */
    public function qiNiuToken()
    {
        // 最简单的处理方式
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: *');

        $accessKey = 'KgCzxHSGM7pTsrTZbQptzoow42e5IcFOMeFrIoQz';
        $secretKey = 'xcloaEa4X3XzqXKDmz_1U1AFtNI1jlbodaHoNOQ4';
        // 初始化签权对象
        $auth = new Auth($accessKey, $secretKey);
        $bucket = 'hongkongidcard';
        // 生成上传Token
        $token = $auth->uploadToken($bucket);
        return array(
            'token' => $token,
            'key' => $secretKey,
            'bucket' => $bucket
        );

    }


    /**
     * 保存签名
     * @desc 保存签名
     * @return array data 签名url
     * @exception 400 非法请求，参数传递错误
     */
    public function SaveImg()
    {
        // 最简单的处理方式
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: *');

        $base64 = $this->base64;
        // $idcard = $this->idcard;

        // return $base64;

        // 保存图片到服务器指定目录
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64, $result)){
            $type = $result[2];
            $new_file = "images/sign/";
            if(!file_exists($new_file)){
                //检查是否有该文件夹，如果没有就创建，并给予最高权限
                mkdir($new_file, 0777);
            }
            $new_file = $new_file.time().".{$type}";
            if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64)))){
                $img_path = "https://api.wenfree.cn/$new_file";


                $accessKey = 'KgCzxHSGM7pTsrTZbQptzoow42e5IcFOMeFrIoQz';
                $secretKey = 'xcloaEa4X3XzqXKDmz_1U1AFtNI1jlbodaHoNOQ4';
                // 初始化签权对象
                $auth = new Auth($accessKey, $secretKey);
                $bucket = 'hongkongidcard';
                // 生成上传Token
                $token = $auth->uploadToken($bucket);
                $uploadMgr = new UploadManager();
                // 构建 BucketManager 对象
                $bucketMgr = new BucketManager($auth);

                $key = 'fibrproHK/images/sign/' . time() . '.png';
                list($ret, $err) = $uploadMgr->putFile($token, $key, $new_file);
                if ($err !== null) {
                    // var_dump($err);
                } else {
                    // return $key;
                }

                return "http://hongkongidcard.wenfree.cn/" . $key;
            }
        }
    }



    /**
     * 保存信息
     * @desc 保存签名
     * @return array data 签名url
     * @exception 400 非法请求，参数传递错误
     */
    public function SaveInfo()
    {
        // 最简单的处理方式
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: *');


        function download ($url,$save_dir='',$filename='',$type=0){
            // 路径是否为空
            if(trim($url)==''){
                return array('file_name'=>'','save_path'=>'','error'=>1);
            }
            //保存到
            if(trim($save_dir)==''){
                $save_dir='./img';
            }
            if(trim($filename)==''){//保存文件名
                $ext=strrchr($url,'.');
                //判断后缀是否合法
                if($ext!='.gif'&& $ext!='.jpeg'){
                    return array('file_name'=>'','save_path'=>'','error'=>3);
                }
                //生成文件名字
                $filename=time().$ext;
            }
            if(0!==strrpos($save_dir,'/')){
                $save_dir.='/';
            }
            //创建保存目录
            if(!file_exists($save_dir)&&!mkdir($save_dir,0777,true)){
                return array('file_name'=>'','save_path'=>'','error'=>5);
            }
            //获取远程文件所采用的方法
            if($type){
                $ch=curl_init();
                $timeout=5;
                curl_setopt($ch,CURLOPT_URL,$url);
                curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
                curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
                $img=curl_exec($ch);
                curl_close($ch);
            }else{
                ob_start();
                readfile($url);
                $img=ob_get_contents();
                ob_end_clean();
            }
            //$size=strlen($img);
            //文件大小
            $fp2=@fopen($save_dir.$filename,'a');
            fwrite($fp2,$img);
            fclose($fp2);
            unset($img,$url);
            return array('file_name'=>$filename,'save_path'=>$save_dir.$filename,'error'=>0);
        }


        $json = file_get_contents('php://input');
        $obj = json_decode($json, true);
        $where = array(
            "idcard" => $obj['idcard'],
        );
        if ( !$obj['names'] ){
            throw new BadRequestException('请输入姓名');
        }
        if ( !$obj['idcard'] ){
            throw new BadRequestException('请输入身份证号');
        }
        if ( !$obj['signature'] ){
            throw new BadRequestException('缺少签名');
        }



        //准备创建word文档
        $word = new TemplateProcessor('templates/sign.docx');

        $courses1=$courses2=$Cash=$Octopus=$PayMe=$msg = '□';
        if ( $obj['courses'] == 'Course Fee HK$193' ){
            $courses1 = '☑';
        }
        if ( $obj['courses'] == 'Course Fee HK$170' ){
            $courses2 = '☑';
        }
        if ( $obj['payment'] == 'Cash' ){
            $Cash = '☑';
        }
        if ( $obj['payment'] == 'Octopus' ){
            $Octopus = '☑';
        }
        if ( $obj['payment'] == 'PayMe' ){
            $PayMe = '☑';
        }
        if ( $obj['msg'] ){
            $msg = '☑';
        }

        $price = $this->getCourse();

        $word->setValue("safety", $price['safety']);
        $word->setValue("Revalidation", $price['Revalidation']);

        $word->setValue("full_name","    ".$obj['f_name']."       ".$obj['l_name'])."    ";
        $word->setValue("courses1", $courses1);
        $word->setValue("courses2", $courses2);
        $word->setValue("Cash", $Cash);
        $word->setValue("Octopus", $Octopus);
        $word->setValue("PayMe", $PayMe);
        $word->setValue("msg", $msg);

        //2.1还可以同时给多个变量同时赋值
        $word->setValues($obj);


        $imgpath = str_replace('https://api.wenfree.cn/', '', $obj['signature']);
        $word->setImageValue('signatures', array(
            'path' => $imgpath,
            'width' => 120,
            'height' => 50,
            'ratio' => false
        ));
        $wordPath = "template/".$obj['names']. '-' .$obj['idcard']."(".$obj['idm'].")".".docx";
        $word->saveAs($wordPath);
        //文档保存结束

        $mail = new PHPMailer(true);
        //服务器配置
        $mail->CharSet ="UTF-8";                     //设定邮件编码
        $mail->SMTPDebug = 0;                        // 调试模式输出
        $mail->isSMTP();                             // 使用SMTP
        $mail->Host = 'smtp.qq.com';                // SMTP服务器
        $mail->SMTPAuth = true;                      // 允许 SMTP 认证
        $mail->Username = 'wenhong520@qq.com';                // SMTP 用户名  即邮箱的用户名
        $mail->Password = 'kvhosrrvyvvsbhge';             // SMTP 密码  部分邮箱是授权码(例如163邮箱)
        $mail->SMTPSecure = 'ssl';                    // 允许 TLS 或者ssl协议
        $mail->Port = 465;                            // 服务器端口 25 或者465 具体要看邮箱服务器支持

        $mail->setFrom('wenhong520@qq.com', '德鑄人力資源發展中心->'.$obj['names']);  //发件人
        $mail->addAddress('eform@mlifeengg.com', '德鑄人力資源發展中心->'.$obj['names']);  // 收件人
        // $mail->addAddress('admin@telegram-bot.top', '德鑄人力資源發展中心->'.$obj['names']);  // 收件人
        if( $obj['self'] ){
            $mail->addAddress($obj['email'], $obj['names']);  // 收件人
        }
        $mail->isHTML(true);                                  // 是否以HTML文档格式发送  发送后客户端可直接显示对应HTML内容
        $mail->Subject = '德鑄人力資源發展中心';    //标题
        $mail->Body    = '<h1>报名表格</h1> ' . date('Y-m-d H:i:s');
        $mail->AltBody = '报名表格' . date('Y-m-d H:i:s');
        if ( $obj['idcard_img'] ){
//            $path = download($obj['idcard_img'], './img', $obj['idcard']. '('. $obj['idm'] .').jpg');
//            throw new BadRequestException($path['save_path']);
//            $mail->addAttachment('img/'. $obj['idcard']. '('. $obj['idm'] .').jpg');
            $mail->Body = '<a href="'.$obj['idcard_img'].'"><img src="'.$obj['idcard_img'].'"></a>';
        }
        $mail->addAttachment($wordPath);
        $mail->send();

        $info = \PhalApi\DI()->notorm->hongkong_info
            ->where($where)
            ->fetchOne();
        if( $info ){
            $obj['update_time'] = date("Y-m-d H:i:s", time());
            return \PhalApi\DI()->notorm->hongkong_info
                ->where('id', $info['id'])->update($obj);
        }
        $obj['create_time'] = date("Y-m-d H:i:s", time());
        return \PhalApi\DI()->notorm->hongkong_info->insert($obj);
    }


    /**
     * 获取七牛上传Token
     * @desc 获取七牛上传Token
     * @return array data 包含token和上传路径
     * @exception 400 非法请求，参数传递错误
     */
    public function getQiniuUploadToken()
    {
        // 设置跨域请求头
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: *');

        // 七牛云配置
        $accessKey = 'KgCzxHSGM7pTsrTZbQptzoow42e5IcFOMeFrIoQz';
        $secretKey = 'xcloaEa4X3XzqXKDmz_1U1AFtNI1jlbodaHoNOQ4';
        $bucket = 'hongkongidcard';
        $key = $this->keys; // 动态获取上传的文件名或路径

        // 初始化签权对象
        $auth = new \Qiniu\Auth($accessKey, $secretKey);

        // 设置上传策略
        $putPolicy = [
            'scope' => $bucket . ':' . $key, // 指定上传的目标存储空间和文件名
        ];

        // 生成上传Token
        $token = $auth->uploadToken($bucket, $key, 3600, $putPolicy);

        // 返回token和上传路径
        return array(
            'token' => $token,
            'key' => $key,
            'bucket' => $bucket,
        );
    }

}
